package com.qf.mvc2203.controller;

import com.qf.mvc2203.ex.UserException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import java.sql.SQLException;

/*
 * 演示异常处理
 * */
@Controller
@RequestMapping("/ex")
public class ExController {
    /*
     * 演示自己写代码处理异常
     * */
    @RequestMapping("/test1")
    public String test1() {
        System.out.println("ExController test1..");
        try {
            int a = 1 / 0;
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            //返回自定义的错误页面
            return "/error/error01.html";
        }

        return "hi.html";
    }

    /*
     * 测试抛出自定义异常
     * */
    @RequestMapping("/test2")
    public String test2() {
        System.out.println("ExController test2..");
        try {
            throw new UserException(001, "用户名重复了");

        } catch (UserException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
            System.out.println(e.getCode());
            System.out.println(e.getMsg());
            return "/error/error02.html";
        } catch (Exception e) {
            return "/error/error01.html";
        }
    }

    /*
     * 测试统一异常处理器能否捕获并处理异常
     * 运行时异常
     * */
    @RequestMapping("/test3")
    public String test3() {
        System.out.println("ExController test3..");
        throw new UserException(001, "用户名重复了");

    }
    /*
     * 测试统一异常处理器能否捕获并处理异常
     * 非运行时异常，直接抛出
     * @return
     */
    @RequestMapping("/test4")
    public String test4() throws SQLException {
        System.out.println("ExController test4..");
        throw new SQLException();

    }

    /*
     *测试统一异常处理器能否捕获并处理异常
     * 异常类型转换
     * */
    @RequestMapping("/test5")

    public String test5() {
        System.out.println("ExController test5..");
        try {
            throw new SQLException();
        } catch (Exception e) {
            e.printStackTrace();
            throw new UserException(1, "用户名重复了");
        }
    }
}
